package com.ego.item.service.impl;

import com.ego.common.pojo.PageResult;
import com.ego.item.bo.SpuBo;
import com.ego.item.mapper.SkuMapper;
import com.ego.item.mapper.SpuDetailMapper;
import com.ego.item.mapper.SpuMapper;
import com.ego.item.mapper.StockMapper;
import com.ego.item.pojo.*;
import com.ego.item.service.BrandService;
import com.ego.item.service.CategoryService;
import com.ego.item.service.GoodsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    /**
    * @Description
    * @Author  luozhonghong
    * @Date   2020/2/24 11:27
    * @Param key关键字 ,saleable 是否上架 0:下架 1：上架,page 当前页,rows 每页显示数量
    * @Return
    * @Exception
    *
    */
    @Override
    public PageResult<SpuBo> page(String key, Boolean saleable, Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //1.关键字查询
        if(StringUtils.isNoneBlank(key)){
            criteria.andLike("title","%"+key+"%").orLike("subTitle","%"+key+"%");
        }
        //2.上下架查询
        criteria.andEqualTo("saleable",saleable);
        //3.排序方式，根据创建日期降序
        example.setOrderByClause("create_time desc");
       Page<Spu> pageInfo=(Page<Spu>) spuMapper.selectByExample(example);
       //将spu转成spuBo
        List<SpuBo> spuBuList = pageInfo.getResult().stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            //将spu中的属性值拷贝到spubo中
            BeanUtils.copyProperties(spu, spuBo);
            //根据类别&品牌id查询出对应名字
            List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
            List<Category> categoryList = categoryService.findListByCids(cids);
            //categoryList-->xx/yy/zz
            List<String> categoryNames = categoryList.stream().map(category -> category.getName()).collect(Collectors.toList());
            spuBo.setCategoryName(StringUtils.join(categoryNames, "/"));
            Brand brand = brandService.findBybid(spu.getBrandId());
            spuBo.setBrandName(brand.getName());
            return spuBo;
        }).collect(Collectors.toList());

        return new PageResult<>(pageInfo.getTotal(),spuBuList);
    }
    @Transactional
    @Override
    public void save(SpuBo spuBo) {
        //1.添加spu
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        spuMapper.insertSelective(spuBo);
        //2.添加spu_detail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        spuDetailMapper.insertSelective(spuDetail);
        //3.添加sku&stock
        if(spuBo.getSkus()!=null&&spuBo.getSkus().size()>0){
            spuBo.getSkus().forEach(sku->{
                sku.setCreateTime(spuBo.getCreateTime());
                sku.setLastUpdateTime(spuBo.getCreateTime());
                sku.setSpuId(spuBo.getId());
                skuMapper.insertSelective(sku);
                sku.getStock().setSkuId(sku.getId());
                stockMapper.insertSelective(sku.getStock());
            });
        }
    }

    @Override
    public SpuDetail findSpuDetailBySpuId(Long spuId) {
        return spuDetailMapper.selectByPrimaryKey(spuId);
    }

    @Override
    public List<Sku> findSkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        return skuMapper.select(sku);
    }

    @Override
    public void update(SpuBo spuBo) {
        //1.修改spu
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);
        //2.修改spu_detail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        //3.删除以前的sku以及stock
        Sku skuExample = new Sku();
        skuExample.setSpuId(spuBo.getId());
        List<Sku> skuList = skuMapper.select(skuExample);
        skuList.forEach(s->{
            skuMapper.deleteByPrimaryKey(s);
            stockMapper.deleteByPrimaryKey(s.getId());
        });
        //4.修改sku&stock
        if(spuBo.getSkus()!=null&&spuBo.getSkus().size()>0){
            spuBo.getSkus().forEach(sku->{
                sku.setId(null);
                sku.setCreateTime(spuBo.getCreateTime());
                sku.setLastUpdateTime(spuBo.getCreateTime());
                sku.setSpuId(spuBo.getId());
                skuMapper.insertSelective(sku);

                sku.getStock().setSkuId(sku.getId());
                stockMapper.insertSelective(sku.getStock());
            });
        }
    }
}
